﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Superbaby.PrettyUI.Forms
{
    public partial class ScrollTextPanel : UserControl
    {
        private string text;
        private float textHeight;

        public ScrollTextPanel()
        {
            InitializeComponent();
        }

        public new string Text
        {
            get
            {
                return this.text;
            }

            set
            {
                this.text = value;

                Rectangle r = new Rectangle(0, 0, this.ClientSize.Width - this.vsb.Width, this.ClientSize.Height);

                //使用API计算文本高度
                using (Graphics g = this.CreateGraphics())
                {
                    this.textHeight = HelperMethods.MeasureStringEx(g, this.text, this.Font, r).Height;
                }


                //禁止滚动条ValueChanged事件，防止控件刷新
                this.vsb.ValueChanged -= vsb_ValueChanged;

                //计算滚动条最大值和Value
                vsb.Minimum = 0;
                if (this.textHeight <= this.ClientSize.Height)
                    vsb.Maximum = 0 - 1 + this.vsb.LargeChange;
                else
                    vsb.Maximum = ((int)(this.textHeight - this.ClientSize.Height)) - 1 + this.vsb.LargeChange;

                vsb.Value = (int)(this.textHeight - this.ClientSize.Height);

                //使控件重绘
                this.Invalidate();

                //恢复ValueChanged事件，在用户拖动滚动条时重绘控件
                this.vsb.ValueChanged += vsb_ValueChanged;
            }
        }

        private void ChatList_Paint(object sender, PaintEventArgs e)
        {
            RectangleF r = new RectangleF(0, -vsb.Value, this.ClientSize.Width - this.vsb.Width, this.textHeight);

            e.Graphics.DrawString(this.text, this.Font, new SolidBrush(Color.Black), r);
        }



        private void vsb_ValueChanged(object sender, EventArgs e)
        {
            this.Invalidate();
        }

        public int HScrollValue
        {
            get { return this.vsb.Value; }
            set { this.vsb.Value = value; }
        }

        public int HScrollLargeChange
        {
            get { return this.vsb.LargeChange; }
            set { this.vsb.LargeChange = value; }
        }
    }
}
